const http = require("http");
const fs = require("fs");
const path = require("path");

const dirPath = path.join(__dirname,process.argv[2]);

http.createServer((req,res) => {
    res.setHeader('content-type','text/html;charset=utf-8');
    fs.open(dirPath,'r',function(err,fd) {
        if (err) {
            console.log("路径文件不存在");
            const readerpath = path.join(__dirname,"/fileReader2.js");
            const readPath = fs.createReadStream(readerpath);
            readPath.pipe(res);
        }
        else{
            console.log('open file success');
            const buffer = new Buffer(255);
            fs.read(fd,buffer,0,255,0,function(err,bytesRead,buffer) {
                if(err) {
                    throw err;
                }
                else {
                    const readable = fs.createReadStream(dirPath);
                    readable.pipe(res);
                    fs.close(fd);
                }
            });
        }
    });
}).listen(8081)

console.log("server is listening 8081");